﻿using AutoMail.QuartzJobs.Interfaces;
using AutoMail.Service.Interface;
using Quartz;

namespace AutoMail.Service
{
    public class QuartzService : IHostedService, IQuartzService
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly ILogger<QuartzService> _logger;

        public static IScheduler Scheduler { get; set; }

        public QuartzService(ISchedulerFactory schedulerFactory, ILogger<QuartzService> logger)
        {
            _schedulerFactory = schedulerFactory;
            _logger = logger;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting Quartz........." + Environment.NewLine);

            if (Scheduler == null)
            {
                Scheduler = await _schedulerFactory.GetScheduler();
            }

            await Scheduler.Start();

            _logger.LogInformation("Starting Finished........." + Environment.NewLine);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Scheduler?.Shutdown(cancellationToken);
        }

        public async Task SchedulingJobs(Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>> currentStaffsMailJobs)
        {
            if (Scheduler == null)
            {
                Scheduler = await _schedulerFactory.GetScheduler();
            }

            await Scheduler.ScheduleJobs(currentStaffsMailJobs, replace: true);
        }

        public IScheduler GetCurrentScheduler()
        {
            return Scheduler;
        }
    }
}
